package com.yh.supergo.zuul.interceptor;

import com.yh.supergo.user.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.security.auth.message.AuthException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName AuthInterceptor
 * @Description 登录权限拦截器
 * @Author 0715-YuHao
 * @Date 2020/11/26 14:59
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器启动。。。");
        String authorization = request.getHeader("Authorization");
        if (authorization == null) {
            throw new AuthException("权限不足");
        }
        if (!authorization.startsWith("Bearer ")) {
            throw new AuthException("权限不足");
        }
        final String token = authorization.substring(7); // The part after "Bearer "
        Claims claims = jwtUtil.parseToken(token);
        if (claims != null) {
            if ("admin".equals(claims.get("roles"))) {//如果是管理员
                request.setAttribute("admin_claims", claims);
            }
            if ("user".equals(claims.get("roles"))) {//如果是用户
                request.setAttribute("user_claims", claims);
            }
        }
        return true;
    }
}
